package top.lyc829.mymusic.model.http

import com.franmontiel.persistentcookiejar.ClearableCookieJar
import com.franmontiel.persistentcookiejar.PersistentCookieJar
import com.franmontiel.persistentcookiejar.cache.SetCookieCache
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor
import com.google.gson.GsonBuilder
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import top.lyc829.mymusic.MyApp
import top.lyc829.mymusic.interceptor.LoggerInterceptor


/**
 * @Author lyc
 * @create 2021-06-28 23:38
 */
object ServiceCreator {

    private const val BASE_URL = "http://192.168.123.132:3000"

    private var cookieJar: ClearableCookieJar =
        PersistentCookieJar(SetCookieCache(), SharedPrefsCookiePersistor(MyApp.context))

    private val httpClient = OkHttpClient
        .Builder()
        .cookieJar(cookieJar)
        //.addNetworkInterceptor(LoggerInterceptor())

    private val retrofit = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .client(httpClient.build())
//        .addConverterFactory(GsonConverterFactory.create(GsonBuilder().registerTypeAdapterFactory(
//            GsonTypeAdapterFactory()
//        ).create()))
        .addConverterFactory(GsonConverterFactory.create(GsonBuilder().setLenient().create()))
        .addConverterFactory(ScalarsConverterFactory.create())
        .build()

    fun <T> create(serviceClass: Class<T>): T = retrofit.create(serviceClass)

    inline fun <reified T> create(): T = create(T::class.java)

}